package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.mapper.PermissionMapper;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;


import java.util.List;

@Service(interfaceClass = PermissionService.class)
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void add(Permission permission) {
        permissionMapper.add(permission);
    }

    /**
     * 查询分页数据
     * @param currentPage
     * @param pageSize
     * @param queryString
     * @return
     */
   /* @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {

        //定义分页查询的起始角标值，limit x，y中的x的值
        int firstResult = (currentPage-1)*pageSize;

        //条件查询总记录数
        Long count = checkItemMapper.findCount(queryString);

        //条件查询分页数据
        List<CheckItem> checkItemList = checkItemMapper.findByCondition(firstResult,pageSize,queryString);

        return new PageResult(count,checkItemList);
    }*/

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {

        //定义页码和页面大小
        PageHelper.startPage(currentPage,pageSize);

        //条件查询数据
        List<Permission> permissions = permissionMapper.findByCondition(queryString);

        //数据包装
        PageInfo<Permission> pageInfo = new PageInfo<>(permissions);


        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 通过id删除检查项
     */
    @Override
    public void deleteById(Integer id) {

        //通过id查询中间表记录，判断该检查项有没有被引用
        Integer count = permissionMapper.findCountByCheckItemId(id);
        if (count>0){
            //如果被引用了，提示用户不能删除的原因
            throw new RuntimeException(MessageConstant.CHECKITEM_IS_QUOTED);
        }
        //如果没有被引用，删除检查项
        permissionMapper.deleteById(id);

    }

    /**
     * 通过id查询检查项
     * @param id
     * @return
     */
    @Override
    public Permission findById(Integer id) {

        return permissionMapper.findById(id);
    }

    /**
     * 编辑更新
     * @param checkItem
     */
    @Override
    public void edit(Permission permission) {
        permissionMapper.edit(permission);
    }

    /**
     * 查询所有检查项
     * @return
     */
    @Override
    public List<Permission> findAll() {
        return permissionMapper.findAll();
    }

    /**
     * 通过检查组id查询检查项的id集合
     * @param id
     * @return
     */
    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {

        return permissionMapper.findCheckItemIdsByCheckGroupId(id);
    }
}
